<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #toolbar>
        <Dropdown placement="bottom">
          <Button type="primary" class="mr-2">添加边缘</Button>
          <template #overlay>
            <Menu @click="addEdgeClick">
              <MenuItem key="newEdge">
                <Icon icon="material-symbols:file-copy-sharp" /> 添加新的边缘</MenuItem
              >
            </Menu>
          </template>
        </Dropdown>
      </template>
      <template #tableTitle>
        <FormItem :style="edgeTypeSelectStyle">
          <span style="margin-right: 10px">边缘类型</span>
          <Select
            style="width: 100px"
            show-search
            v-model:value="edgeTypeSelectValue"
            :options="edgeTypeSelectList"
            @change="getEdgeTypeSelect"
            :show-arrow="true"
          />
        </FormItem>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:edit-filled',
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:eye-filled',
                tooltip: {
                  title: '详情',
                  placement: 'top',
                },
                onClick: handleMore.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: handleDelete.bind(null, record),
              },
            ]"
            :drop-down-actions="[
              {
                icon: 'ic:sharp-share',
                label: '公开',
                disabled: record.customerIsPublic,
                onClick: handleOpen.bind(null, record),
              },
              {
                icon: 'material-symbols:person-pin',
                label: '分配给客户',
                disabled: record.customerIsPublic || record.customerTitle !== null,
                onClick: AssignToCustomers.bind(null, record),
              },
              {
                icon: 'mdi:arrow-left-bold-box',
                label: '取消分配给客户',
                disabled: record.customerIsPublic || record.customerTitle === null,
                onClick: unassignToCustomer.bind(null, record),
              },
              {
                icon: 'octicon:reply',
                label: '私有',
                disabled: !record.customerIsPublic,
                onClick: handlePrivate.bind(null, record),
              },
              {
                icon: 'ant-design:property-safety-outlined',
                label: '管理资产',
                onClick: handleProperty.bind(null, record),
              },
              {
                icon: 'material-symbols:devices-outline-sharp',
                label: '管理设备',
                onClick: handleDevices.bind(null, record),
              },
              {
                icon: 'material-symbols:view-comfy',
                label: '实体视图',
                onClick: entityView.bind(null, record),
              },
              {
                icon: 'ri:function-line',
                label: '管理仪表板',
                onClick: handleLine.bind(null, record),
              },
              {
                icon: 'akar-icons:link-chain',
                label: '管理规则链',
                onClick: handleRuleChain.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <PublicDrawer @register="registerDrawer" @updateDescData="handleUpdateDescData" />
    <AddEdgeModal @register="addRegisterModal" @close-add-edge-flag="closeAddEdgeFlag" />
    <AssignToCustomer @register="toCustomersRegisterModal" @close-flag="closeToCustomerFlag" />
  </div>
</template>

<script lang="ts" setup>
  import { ICON } from '/@/enums/iconEnum';
  import { Alert, Tooltip } from 'ant-design-vue';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { edgeColumns, searchFormSchema, detailSchema } from '../edge.data';
  import { Select, FormItem, Dropdown, Button, Menu, MenuItem } from 'ant-design-vue';
  import {
    getEdgeList,
    deleteTheEdge,
    getTheEdgeData,
    isPrivate,
    isOpen,
    getEdgeTypeList,
  } from '/@/api/thingsborad/edge/edge';
  import AssignToCustomer from './AssignToCustomers.vue';
  import { edgeParams } from '/@/api/thingsborad/edge/model/edgeModel';
  import { onMounted, ref } from 'vue';
  import { useModal } from '/@/components/Modal';
  import dayjs from 'dayjs';
  import Icon from '/@/components/Icon/src/Icon.vue';
  import AddEdgeModal from './AddEdgeModal.vue';
  import { v4 as uuidv4 } from 'uuid';
  import { generateRandomString } from '/@/components/thingsborad/sharedComponents/method/utils';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDrawer } from '/@/components/Drawer';
  import { useGo } from '/@/hooks/web/usePage';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  const go = useGo();

  const { createConfirm } = useMessage();
  //下拉表单
  let edgeTypeSelectList = ref<Array<any>>([]);
  let edgeTypeSelectValue = ref<any>('全部');

  //样式
  let edgeTypeSelectStyle = ref<any>({
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  });

  // 表格数据
  let edgeTableDataList = ref<Array<any>>([]);

  //参数
  let params = ref<edgeParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'createdTime',
    sortOrder: 'DESC',
    type: '',
  });

  //是否全选
  const checkedKeys = ref<any>([]);

  // 表单内容 仓库
  onMounted(() => {
    //初始化 表格数据
    setProps({
      api: getEdgeList,
      beforeFetch: (val) => {
        params.value.page = val.page - 1;
        params.value.pageSize = val.pageSize;
        params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
        params.value.sortProperty = 'createdTime';

        if (val.deptName === null) {
          params.value.textSearch = undefined;
        } else {
          params.value.textSearch = val.deptName;
        }
        return params.value;
      },
      afterFetch: (res) => {
        edgeTableDataList.value = [];
        if (res.length === 0) {
          return edgeTableDataList.value;
        }
        res.forEach((item) => {
          edgeTableDataList.value.push({
            createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
            name: item.name,
            type: item.type,
            label: item.label,
            customerTitle: item.customerTitle,
            customerIsPublic: item.customerIsPublic,
            id: item.id.id,
            info: item,
          });
        });
        return edgeTableDataList.value;
      },
      fetchSetting: {
        pageField: 'page',
        sizeField: 'pageSize',
        listField: 'data',
        totalField: 'totalElements',
      },
    });
    // 初始化边缘类型
    getEdgeTypeDataList();
  });

  const [registerDrawer, { openDrawer }] = useDrawer();

  const [addRegisterModal, { openModal: addOpenModal, setModalProps: addSetModalProps }] =
    useModal();

  const [
    toCustomersRegisterModal,
    { openModal: toCustomersOpenModal, setModalProps: toCustomersModalProps, closeModal },
  ] = useModal();

  //获取边缘类型
  async function getEdgeTypeDataList() {
    edgeTypeSelectList.value = [];
    const edgeTypeListData = await getEdgeTypeList();

    edgeTypeListData.forEach((item) => {
      edgeTypeSelectList.value.push({
        label: item.type,
        value: item.type,
      });
    });
    edgeTypeSelectList.value.unshift({
      label: '全部',
      value: '',
    });
  }
  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    columns: edgeColumns,
    ...tableStyleSetting,
    formConfig: {
      layout: 'horizontal',
      schemas: searchFormSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 16 },
        lg: { span: 6, offset: 16 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除  '${checkedKeys.value.length}' 个边缘吗？`,
      content: '当心, 确认后，选定的边缘以及所有关联数据将不可恢复。',
      onOk: async () => {
        for (const item of checkedKeys.value) {
          await deleteTheEdge(item);
        }
        checkedKeys.value = [];
        reload();
      },
    });
  };

  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  function getEdgeTypeSelect(value) {
    
    params.value.type = value;
    reload();
  }

  //公开
  function handleOpen(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定确定要将边缘 ${record.name}  设为公开吗？`,
      content: '确认后，边缘及其所有数据将被设为公开并可被其他人访问。',
      onOk: async () => {
        await isPrivate(record.id);

        reload();
      },
    });
  }
  //分配给客户
  function AssignToCustomers(record: Recordable) {
    toCustomersModalProps({
      title: '分配边缘给客户',
      okText: '分配',
    });
    toCustomersOpenModal(true, record);
  }
  // 取消分配给客户
  function unassignToCustomer(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定取消分配边缘  ${record.name}  吗？`,
      content: '确定后，边缘将被取消分配，并且客户将无法访问。',
      onOk: async () => {
        await isOpen(record.id);

        reload();
      },
    });
  }
  // 私有
  function handlePrivate(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定确定要将边缘 ${record.name}  设为私有吗？`,
      content: '确认后，边缘及其所有数据将被设为私有，不被其他人访问。',
      onOk: async () => {
        await isOpen(record.id);

        reload();
      },
    });
  }
  // 资产
  function handleProperty(record: Recordable) {
    go({
      name: 'Asset',
      params: {
        id: record.id,
        name: record.name,
        key: '边缘实例',
      },
    });
  }
  // 设备
  function handleDevices(record: Recordable) {
    go({
      name: 'Devices',
      params: {
        id: record.id,
        name: record.name,
        key: '边缘实例',
      },
    });
  }
  // 实体视图
  function entityView(record: Recordable) {
    go({
      name: 'Views',
      params: {
        id: record.id,
        name: record.name,
        key: '边缘实例',
      },
    });
  }
  // 仪表盘
  function handleLine(_record: Recordable) {}
  // 规则链
  function handleRuleChain(record: Recordable) {
    go({
      name: 'TbrulePage',
      params: {
        id: record.id,
      },
    });
  }

  function handleEdit(record: Recordable) {
    addSetModalProps({
      title: '编辑边缘',
      okText: '保存',
      width: '548px',
    });
    addOpenModal(true, { key: uuidv4(), password: generateRandomString(20), record: record });
  }
  function handleMore(record: Recordable) {
    openDrawer(true, {
      entityType: ENTITY_TYPE.EDGE_INSTANCE,
      entityId: record.id,
      title: record.name,
      api: getTheEdgeData,
      detailSchema: detailSchema,
      params: record.id,
    });
  }
  // 删除
  async function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定删除边缘 名称${record.name} 吗？`,
      content: '当心, 确认后，边缘以及所有关联数据将不可恢复。',
      onOk: async () => {
        await deleteTheEdge(record.id);
        reload();
      },
    });
  }
  // 添加边缘
  function addEdgeClick(value) {
    if (value.key === 'newEdge') {
      addSetModalProps({
        title: '添加边缘',
        okText: '添加',
        width: '548px',
      });
      addOpenModal(true, { key: uuidv4(), password: generateRandomString(20) });
    }
  }
  // 组件通信 关闭 添加边缘弹窗
  function closeAddEdgeFlag() {
    //初始化 表格数据
    reload();
    getEdgeTypeDataList();
  }
  // 组件通信 关闭 添加边缘弹窗
  function closeToCustomerFlag() {
    //初始化 表格数据
    closeModal();
    reload();
  }

  const handleUpdateDescData = (value) => {
    value.assetName = value.name;
    value.assetConfiguration = value.assetProfileName;
    value.label = value.label;
    value.customer = value.customerTitle;
    value.isOpen = value.customerIsPublic;
  };
</script>
